package com.autoagent.ai_live_master.webSocket.service;

import com.autoagent.ai_live_master.scriptGeneration.entity.CompleteScripts;
import com.autoagent.ai_live_master.scriptGeneration.service.CompleteScriptsService;
import com.autoagent.ai_live_master.scriptRecommendation.entity.LiveStreamingPlan;
import com.autoagent.ai_live_master.scriptRecommendation.service.LiveStreamingPlanService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 定式话术服务
 * 负责根据直播间房号获取对应的定式话术内容
 */
@Slf4j
@Service
public class FormulaicScriptService {

    @Autowired
    private LiveStreamingPlanService liveStreamingPlanService;

    @Autowired
    private CompleteScriptsService completeScriptsService;

    @Autowired
    private ObjectMapper objectMapper;

    // 缓存已获取的定式话术，避免重复查询
    // 房间ID -> 定式话术内容
    private final ConcurrentMap<String, String> formulaicScriptCache = new ConcurrentHashMap<>();

    /**
     * 根据直播间房号获取定式话术内容
     * 只在入口处调用一次，后续使用缓存
     * 
     * @param roomId 直播间房号
     * @return 定式话术内容，如果未找到则返回空字符串
     */
    public String getFormulaicScriptByRoomId(String roomId) {
        // 先检查缓存
        String cachedScript = formulaicScriptCache.get(roomId);
        if (cachedScript != null) {
            log.debug("从缓存获取定式话术，房间ID: {}", roomId);
            return cachedScript;
        }

        try {
            log.info("开始获取定式话术，房间ID: {}", roomId);
            
            // 1. 根据房间ID查找直播计划
            LiveStreamingPlan plan = liveStreamingPlanService.findEnabledPlanByRoomId(roomId);
            if (plan == null) {
                log.warn("未找到对应的直播计划，房间ID: {}", roomId);
                return "";
            }

            // 2. 获取scriptId
            Long scriptId = plan.getScriptId();
            if (scriptId == null) {
                log.warn("直播计划中未配置scriptId，房间ID: {}, 计划ID: {}", roomId, plan.getId());
                return "";
            }

            // 3. 根据scriptId获取脚本文本
            CompleteScripts script = completeScriptsService.getScriptById(scriptId);
            if (script == null) {
                log.warn("未找到对应的话术内容，scriptId: {}", scriptId);
                return "";
            }

            String scriptContent = script.getContent();
            if (scriptContent == null || scriptContent.trim().isEmpty()) {
                log.warn("话术内容为空，scriptId: {}", scriptId);
                return "";
            }

            // 3. 缓存结果
            formulaicScriptCache.put(roomId, scriptContent);
            log.info("成功获取定式话术，房间ID: {}, scriptId: {}, 内容长度: {}", 
                    roomId, scriptId, scriptContent.length());

            return scriptContent;

        } catch (Exception e) {
            log.error("获取定式话术失败，房间ID: {}, 错误信息: {}", roomId, e.getMessage(), e);
            return "";
        }
    }


    /**
     * 清除指定房间的缓存
     * 
     * @param roomId 房间ID
     */
    public void clearCache(String roomId) {
        formulaicScriptCache.remove(roomId);
        log.info("清除定式话术缓存，房间ID: {}", roomId);
    }

    /**
     * 清除所有缓存
     */
    public void clearAllCache() {
        formulaicScriptCache.clear();
        log.info("清除所有定式话术缓存");
    }

    /**
     * 获取缓存大小（用于监控）
     */
    public int getCacheSize() {
        return formulaicScriptCache.size();
    }
}
